package com.hqw.jzdemo.view;

import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.fengfei.ffadsdk.AdViews.Native.FFNativeInfo;
import com.fengfei.ffadsdk.AdViews.Native.FFNativeLoadListener;
import com.fengfei.ffadsdk.AdViews.Native.FFNativeManager;
import com.fengfei.ffadsdk.AdViews.Native.FFNativeShowListener;
import com.fengfei.ffadsdk.AdViews.Native.FFNativeViewContainer;
import com.fengfei.ffadsdk.AdViews.Splash.FFSpalshListener;
import com.fengfei.ffadsdk.Common.Util.FFAdLogger;
import com.hqw.jzdemo.BuildConfig;
import com.hqw.jzdemo.MainActivity;
import com.hqw.jzdemo.R;
import com.hqw.jzdemo.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

import static com.hqw.jzdemo.util.Util.showToast;

//import com.facebook.react.views.webview.events.TopLoadingFinishEvent;

/**
 * ReactJzAdView
 *
 * Created by tiangui on 2020/01/13.
 */
public class ReactJzAdView2 extends LinearLayout {

    private static final String TAG = "ReactNative-jz";

    private ReactContext mContext;
    private AQuery mAQuery;
    private FFNativeViewContainer mContainer;
    private FFNativeManager mNativeManager;
    private FFNativeInfo mAdInfo;

    public ReactJzAdView2(ReactContext context, AttributeSet set) {
        super(context, set);

        mContext = context;

        LayoutInflater layoutInflater = context.getCurrentActivity().getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.view_react_jz_ad_2, this);
        mAQuery = new AQuery(findViewById(R.id.root));
        mContainer = view.findViewById(R.id.custom_native_container);

//        mNativeManager = ((MainActivity) mContext.getCurrentActivity()).getFFNativeManager();

        initView();
    }

    private void initView() {
        LogUtil.i(TAG, "initView()");

        mContainer.addOnAttachStateChangeListener(new OnAttachStateChangeListener(){
            @Override
            public void onViewAttachedToWindow(View v) {
                LogUtil.i(TAG, "onViewAttachedToWindow()");
            }

            @Override
            public void onViewDetachedFromWindow(View v) {
                LogUtil.i(TAG, "onViewDetachedFromWindow()");
            }
        });

    }

    // TODO  可能需要 check mContext 的有效性
    public void requestAd() {
        loadAd();
    }

    private void loadAd() {
        Log.i(TAG, "loadAd()");
        if (mNativeManager != null) {
            mNativeManager.destroy();
            mNativeManager = null;
        }
        // Note: 每次请求信息流广告都需要生成一个新的 FFNativeManager
        mNativeManager = new FFNativeManager(mContext.getCurrentActivity());
        mNativeManager.requestAd(mContext, BuildConfig.appId, BuildConfig.nativeId, new FFNativeLoadListener() {
            @Override
            public void onNativeAdReceived(ArrayList<FFNativeInfo> infoArrayList) {
                Log.i("FFAd-native", "onNativeAdReceived()");
                mAdInfo = infoArrayList.get(0);
                initAd(mAdInfo);
                showToast(mContext, "数据请求完毕: " + infoArrayList.size());
            }

            @Override
            public void onNativeAdReceiveFailed(String failReason) {
                Log.e("FFAd-native", "onNativeAdReceived(): " + failReason);
                mAdInfo = null;
                showToast(mContext, "数据请求失败 " + failReason);
            }

            @Override
            public void onDownloadStatusChange(int status) {

            }
        }, true);
    }

    private void initAd(FFNativeInfo ad) {
        Log.i(TAG, "initAd()");
        // 出现在屏幕内后调用
        renderAd(ad);

        int adType = ad.getAdType(); // 广告类型
        Log.i("FFAd-native", "adType: " + adType);
        List<View> clickableViews = new ArrayList<>();
        // Note: 这里只处理单图的情况
        if (adType == 1) {
            clickableViews.add(mContainer); // TODO 点击这个不行

            clickableViews.add(findViewById(R.id.custom_native_img));
            clickableViews.add(findViewById(R.id.custom_native_title));
            clickableViews.add(findViewById(R.id.custom_native_desc));
        }

        mNativeManager.showAd(mContainer, clickableViews, new FFNativeShowListener() {
            @Override
            public void onNativeAdShowFail(String failReason) {
                FFAdLogger.e("FFNativeManager.onNativeAdShowFail(): " + failReason);
            }

            @Override
            public void onNativeAdClicked() {
                FFAdLogger.i("FFNativeManager.onNativeAdClicked()");
            }

            @Override
            public void onNativeAdExposured() {
                FFAdLogger.i("FFNativeManager.onNativeAdExposured()");
            }
        });

    }

    private void renderAd(FFNativeInfo ad) {
        Log.i(TAG, "renderAd()");
        int adType = ad.getAdType(); // 0 模版; 1 单图; 2 三小图; 3 视频
        // Note: 这里只处理单图的情况
        if (adType == 1) {
            mAQuery.id(R.id.custom_native_img).image(ad.getkAdImageUrl(), false, true);
            mAQuery.id(R.id.custom_native_title).text(ad.getkAdTitle());
            mAQuery.id(R.id.custom_native_desc).text(ad.getkAdDesc());
        }
    }

    /**
     * copy from ReactWebViewManager.java
     */
    public static void emitFinishEvent(ReactJzAdView2 alignedTextView, int contentHeight) {
//        dispatchEvent(
//                alignedTextView,
//                new TopLoadingFinishEvent(
//                        alignedTextView.getId(),
//                        createWebViewEvent(alignedTextView, contentHeight)));
    }

    private static void dispatchEvent(ReactJzAdView2 alignedTextView, Event event) {
        ReactContext reactContext = (ReactContext) alignedTextView.getContext();
        EventDispatcher eventDispatcher =
                reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
        eventDispatcher.dispatchEvent(event);
    }

    private static WritableMap createWebViewEvent(ReactJzAdView2 alignedTextView, int contentHeight) {
        WritableMap event = Arguments.createMap();

        event.putInt("target", alignedTextView.getId());
        event.putDouble("contentHeight", contentHeight);

        return event;
    }

}
